package com.spark.data

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v4.app.DialogFragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.colliery.common.ext.gone
import com.spark.colliery.common.ext.isVisible
import com.spark.colliery.common.ext.watchWithClear
import com.spark.common.Api
import com.spark.common.App
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.error
import com.spark.common.ext.report
import com.spark.common.ext.wrapIO
import com.spark.common.model.db.QrHistoryModel
import com.spark.common.model.db.QrHistoryModel_
import com.spark.data.model.MaterialQrResultListModel
import io.objectbox.rx.RxQuery
import io.reactivex.Single
import kotlinx.android.synthetic.main.frag_data_query.*
import me.yokeyword.fragmentation.SupportHelper

/**
 * 资料检索-结果页
 */
class DataQueryResultFragment : BaseFragment() {
    private var dataQrSearchFragment: DataQrSearchFragment? = null
    private var dataQrFilterFragment: NotifyHistoryFilterFragment? = null

    private lateinit var querAdapter: QueryAdapter
    private var keyword = ""
    private var currPage = 1

    companion object {
        fun newInstance(keyword: String): DataQueryResultFragment {
            val target = DataQueryResultFragment()
            val args = Bundle()
            args.putString(Const.qr_keyswords, keyword)
            target.arguments = args
            return target
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_data_query
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        keyword = arguments?.getString(Const.qr_keyswords) ?: ""

        iv_back.setOnClickListener { pop() }
        et_search.watchWithClear(iv_delete)
        iv_delete.setOnClickListener { et_search.setText("") }
        /**
         * icon -search
         */
        et_search.setOnTouchListener { _, _ ->
            dataQrSearchFragment = DataQrSearchFragment.newInstance()
            dataQrSearchFragment?.show(childFragmentManager, DataQrSearchFragment.javaClass.simpleName)
            dataQrSearchFragment?.addQueryListener {
                if (!it.isNullOrBlank()) {
                    currPage = 1
                    fetchMaterials(page = currPage, keywords = it ?: "")
                }
            }
            return@setOnTouchListener true
        }
        /**
         * icon -category
         */
        iv_category.setOnClickListener { _ ->
            dataQrFilterFragment = DataQrFilterFragment.newInstance()
            dataQrFilterFragment?.show(childFragmentManager, DataQrFilterFragment.javaClass.simpleName)
            dataQrFilterFragment?.addSearchActionListener {
                currPage = 1
                fetchMaterials(scopedConetntId = it.scopendContentId, keywords = it.keyword, brands = it.brands, startTime = it.startTime, endTime = it.endTime, page = currPage)
            }


        }

        refresh_layout.setOnLoadmoreListener {
            currPage++
            //fetchMaterials(page = currPage, keywords = keyword)
            refresh_layout.finishLoadmore()
        }
        refresh_layout.setOnRefreshListener {
            currPage = 1
            //fetchMaterials(page = currPage, keywords = keyword)
            refresh_layout.finishRefresh()
        }

        querAdapter = QueryAdapter(R.layout.item_borrow_list)
        recy_datas.adapter = querAdapter
        recy_datas.layoutManager = LinearLayoutManager(context)
        // fake data
        querAdapter.addData(mutableListOf(
                MaterialQrResultListModel.ResultMap(button = "借阅", name = "安全生产标准试行办法", number = "20-10-01", stdname = "安全生产标准试行办法", keys = "安全、标准"),
                MaterialQrResultListModel.ResultMap(button = "借阅", name = "安全生产标准试行办法", number = "20-10-01", stdname = "安全生产标准试行办法", keys = "安全、标准"),
                MaterialQrResultListModel.ResultMap(button = "借阅", name = "安全生产标准试行办法", number = "20-10-01", stdname = "安全生产标准试行办法", keys = "安全、标准"),
                MaterialQrResultListModel.ResultMap(button = "借阅", name = "安全生产标准试行办法", number = "20-10-01", stdname = "安全生产标准试行办法", keys = "安全、标准")
        ))
        querAdapter.setOnItemChildClickListener { _, _, position ->
            val data = querAdapter.data[position]
            val itemStr = Gson().toJson(data)
            start(BorrowApplyInfoFragment.newInstance(itemStr))
        }
    }

    override fun onEnterAnimationEnd(savedInstanceState: Bundle?) {
        super.onEnterAnimationEnd(savedInstanceState)
        fetchMaterials(page = currPage, keywords = keyword)
    }


    override fun onBackPressedSupport(): Boolean {
        if (dataQrSearchFragment?.isVisible == true) {
            dataQrSearchFragment?.dismiss()
            return true
        }
        if (dataQrFilterFragment?.isVisible == true) {
            dataQrFilterFragment?.dismiss()
            return true
        }
        return super.onBackPressedSupport()
    }


    /**
     * 点击搜索，获取检索资料
     */
    @SuppressLint("CheckResult")
    private fun fetchMaterials(scopedConetntId: String = "", keywords: String = "", brands: String = "", startTime: String = "", endTime: String = "", page: Int) {
        Api.getEditionList(scopedContentId = scopedConetntId, keywords = keywords, brands = brands, startTime = startTime, endTime = endTime, page = "$page")
                .subscribe(
                        {
                            Gson().fromJson(it, MaterialQrResultListModel::class.java)?.apply {
                                if (code == "200") {
                                    if (page == 1)
                                        querAdapter.data.clear()
                                    querAdapter.addData(resultMaps)
                                } else {
                                    error(msg)
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            if (page == 1) refresh_layout.finishRefresh() else refresh_layout.finishLoadmore()
                        },
                        {
                            if (page == 1) refresh_layout.finishRefresh() else refresh_layout.finishLoadmore()
                        },
                        {
                            dispose = it
                        }
                )
    }
}

class QueryAdapter(@LayoutRes layoutRes: Int) : BaseQuickAdapter<MaterialQrResultListModel.ResultMap, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: MaterialQrResultListModel.ResultMap?) {
        helper?.apply {
            if (item == null) return
            setText(R.id.tv_name, item.name)
            setText(R.id.tv_state, item.state)
            setText(R.id.tv_serial, "编号：${item.number}")
            setText(R.id.tv_regular, "规范：${item.stdname}")
            //setText(R.id.tv_created, "创建：${sdf().format(item.timestamp)}")
            setText(R.id.tv_created, "创建：2018年3月24日 18:32:45")
            //setText(R.id.tv_tags, "标签：${item.keysName}")
            setText(R.id.tv_tags, "标签：安全、标准")

            getView<TextView>(R.id.tv_apply_detail).apply {
                background = resources.getDrawable(R.drawable.bg_round10_solid_rect_blue)
                text = "申请查阅"
                setTextColor(resources.getColor(R.color.white))
            }
            val rlInfo = getView<RelativeLayout>(R.id.rl_info)
            rlInfo.gone(true)
            getView<ImageView>(R.id.iv_expand).setOnClickListener {
                val state = rlInfo.isVisible()
                rlInfo.gone(state)
            }

            val recyBooks = getView<RecyclerView>(R.id.recy_books)
            recyBooks.layoutManager = object : LinearLayoutManager(mContext) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            val queryBookAdapter = QueryBookAdapter(R.layout.item_borrow_book, false)
            recyBooks.adapter = queryBookAdapter
            queryBookAdapter.addData(item.fileList)
            queryBookAdapter.addData(mutableListOf(
                    MaterialQrResultListModel.ResultMap.File(),
                    MaterialQrResultListModel.ResultMap.File(),
                    MaterialQrResultListModel.ResultMap.File(),
                    MaterialQrResultListModel.ResultMap.File()
            ))

            getView<TextView>(R.id.tv_apply_detail).setOnClickListener {
                onItemChildClickListener?.onItemChildClick(this@QueryAdapter, it, adapterPosition)
            }
        }
    }

}

class QueryBookAdapter(layoutRes: Int, var eyeOpen: Boolean = true) : BaseQuickAdapter<MaterialQrResultListModel.ResultMap.File, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: MaterialQrResultListModel.ResultMap.File?) {
        if (item == null) return
        helper?.apply {
            //setText(R.id.tv_name, item.filename)
            setText(R.id.tv_name, "煤矿安全生产标准试行办法")
            setGone(R.id.ll_eye, eyeOpen)
        }
    }

}

/**
 * <><><><><><><><><><><><><><>数据检索 搜索历史Dialog
 */
class DataQrSearchFragment : DialogFragment() {
    private lateinit var searchHistoryAdapter: SearchHistoryAdapter
    private var queryListener: OnQueryListener? = null
    private val qrHistoryBox = App.boxStore.boxFor(QrHistoryModel::class.java)

    companion object {
        fun newInstance(): DataQrSearchFragment {
            val fragment = DataQrSearchFragment()
            val args = Bundle()

            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFragmentAnimStyle)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.dal_data_qr_search, container)
    }

    @SuppressLint("CheckResult")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val recyHistory = view.findViewById<RecyclerView>(R.id.recy_data_search_history)
        val ctlHistory = view.findViewById<RelativeLayout>(R.id.rl_history_ctrl)

        searchHistoryAdapter = SearchHistoryAdapter(R.layout.item_dal_data_qr_search)
        recyHistory.adapter = searchHistoryAdapter
        recyHistory.layoutManager = LinearLayoutManager(context)
        /**
         * Query the keywords has been used to search
         */
        RxQuery.observable(qrHistoryBox.query().build())
                .wrapIO()
                .subscribe(
                        {
                            val empty = it.isEmpty()
                            recyHistory.gone(empty)
                            ctlHistory.gone(empty)
                            searchHistoryAdapter.data.clear()
                            searchHistoryAdapter.addData(it)
                        },
                        {
                            it.printStackTrace()
                            report(it)
                        },
                        {},
                        {}
                )

        /**
         * step 1: click to search
         * step 2: sort the order of keyword
         */
        searchHistoryAdapter.setOnItemClickListener { adapter, view, position ->
            val key = searchHistoryAdapter.data[position]
            queryListener?.onQuery(key.keyword)
            qrHistoryBox.apply {
                val storeValues = query().equal(QrHistoryModel_.keyword, key.keyword).build().find()
                remove(storeValues)
                put(key)
            }
            dismissAllowingStateLoss()
        }
        /**
         * clear data
         */
        view.findViewById<TextView>(R.id.tv_clear_history).setOnClickListener {
            searchHistoryAdapter.data.clear()
            searchHistoryAdapter.notifyDataSetChanged()
            recyHistory.gone(true)
            ctlHistory.gone(true)
            Single.create<Boolean> {
                qrHistoryBox.removeAll()
            }
                    .wrapIO()
                    .subscribe(
                            {
                                // do nothing
                            },
                            {
                                report(it)
                                LogUtils.d("failed to delete all of the history of the search keyword")
                            }
                    )

        }
        /**
         * shut down the window
         */
        view.findViewById<TextView>(R.id.tv_close).setOnClickListener {
            dismissAllowingStateLoss()
        }

        val etSearch = view.findViewById<EditText>(R.id.et_search)
        val ivDel = view.findViewById<ImageView>(R.id.iv_delete)
        val tvSearch = view.findViewById<TextView>(R.id.tv_search)
        etSearch.watchWithClear(ivDel)

        ivDel.setOnClickListener { etSearch.setText("") }
        /**
         * the search icon been clicked
         */
        tvSearch.setOnClickListener {
            val keyword = etSearch.text.toString().trim()
            queryListener?.onQuery(keyword)
            if (!keyword.isNullOrBlank()) {
                qrHistoryBox.apply {
                    val storeValues = query().equal(QrHistoryModel_.keyword, keyword).build().find()
                    remove(storeValues)
                    put(QrHistoryModel(keyword = keyword))
                }
            }
            dismissAllowingStateLoss()
        }
        /**
         * decorview touch
         */
        dialog.window.decorView.setOnTouchListener { _, _ ->
            dismissAllowingStateLoss()
            return@setOnTouchListener true
        }
    }

    override fun onDismiss(dialog: DialogInterface?) {
        SupportHelper.hideSoftInput(this@DataQrSearchFragment.dialog.window.decorView)
        super.onDismiss(dialog)
    }

    /**
     * add click listner
     */
    fun addQueryListener(listener: (String?) -> Unit) {
        queryListener = object : OnQueryListener {
            override fun onQuery(key: String?) {
                listener(key)
            }
        }
    }

    /**
     * when click the keyword on the history list,transport the envet
     */
    interface OnQueryListener {
        fun onQuery(key: String?)
    }

    /**
     * the adapter of the query keywords
     */
    class SearchHistoryAdapter(@LayoutRes layoutRes: Int) : BaseQuickAdapter<QrHistoryModel, BaseViewHolder>(layoutRes) {
        override fun convert(helper: BaseViewHolder?, item: QrHistoryModel?) {
            if (item == null) return
            helper?.apply {
                setText(R.id.tv_query_name, item.keyword)
            }
        }

    }
}

